import type { Chapter } from "@/types";

// TXT转Mock数据的配置选项
export interface TxtToMockOptions {
  novelId?: string;
  novelTitle?: string;
  freeChapters?: number;
  vipPrice?: number;
  chunkSize?: number;
}

// 默认配置
const DEFAULT_OPTIONS: Required<TxtToMockOptions> = {
  novelId: "novel",
  novelTitle: "小说",
  freeChapters: 50,
  vipPrice: 50000,
  chunkSize: 1024 * 1024, // 1MB
};

/**
 * 将TXT内容转换为Mock章节数据
 * @param txtContent TXT文件内容
 * @param options 配置选项
 * @returns 章节数据数组
 */
export function convertTxtToMock(txtContent: string, options: TxtToMockOptions = {}): Chapter[] {
  const config = { ...DEFAULT_OPTIONS, ...options };

  // 分割章节 - 支持多种章节标题格式
  const chapterRegex = /(第[一二三四五六七八九十百千万零\d]+章[^\n]*)/g;
  const chapters = txtContent.split(chapterRegex).filter(Boolean);

  const result: Chapter[] = [];
  let chapterCount = 0;

  for (let i = 0; i < chapters.length; i += 2) {
    const chapterTitle = chapters[i]?.trim();
    const chapterContent = chapters[i + 1]?.trim();

    if (!chapterTitle || !chapterContent) continue;

    chapterCount++;

    result.push({
      id: `${config.novelId}-${chapterCount}`,
      novelId: config.novelId,
      chapterNumber: chapterCount,
      title: `${config.novelTitle} ${chapterTitle}`,
      content: chapterContent,
      wordCount: countChineseCharacters(chapterContent),
      isVip: chapterCount > config.freeChapters,
      price: chapterCount > config.freeChapters ? config.vipPrice : 0,
      isFree: chapterCount <= config.freeChapters,
      createdAt: generateRandomDate(),
      updatedAt: generateRandomDate(),
    });
  }

  return result;
}

/**
 * 处理大型TXT文件（分块处理）
 * @param file File对象
 * @param options 配置选项
 * @returns Promise<Chapter[]>
 */
export async function processLargeTxt(
  file: File,
  options: TxtToMockOptions = {},
): Promise<Chapter[]> {
  const config = { ...DEFAULT_OPTIONS, ...options };
  const result: Chapter[] = [];
  let chapterCount = 0;
  let offset = 0;
  let remaining = "";

  while (offset < file.size) {
    const chunk = await readFileChunk(file, offset, config.chunkSize);
    const content = remaining + chunk;

    // 分割章节
    const chapterRegex = /(第[一二三四五六七八九十百千万零\d]+章[^\n]*)/g;
    const chapters = content.split(chapterRegex).filter(Boolean);

    // 处理完整章节（保留最后一个可能不完整的章节）
    const completeChapters = chapters.length > 2 ? chapters.slice(0, -2) : [];

    for (let i = 0; i < completeChapters.length; i += 2) {
      const chapterTitle = completeChapters[i]?.trim();
      const chapterContent = completeChapters[i + 1]?.trim();

      if (!chapterTitle || !chapterContent) continue;

      chapterCount++;
      result.push(createChapterObject(chapterCount, chapterTitle, chapterContent, config));
    }

    // 保存可能不完整的部分到下次处理
    remaining = chapters.length >= 2 ? chapters.slice(-2).join("") : chapters.join("");
    offset += chunk.length;
  }

  // 处理最后剩余的内容
  if (remaining.trim()) {
    const finalChapters = remaining
      .split(/(第[一二三四五六七八九十百千万零\d]+章[^\n]*)/g)
      .filter(Boolean);

    for (let i = 0; i < finalChapters.length; i += 2) {
      const chapterTitle = finalChapters[i]?.trim();
      const chapterContent = finalChapters[i + 1]?.trim();

      if (!chapterTitle || !chapterContent) continue;

      chapterCount++;
      result.push(createChapterObject(chapterCount, chapterTitle, chapterContent, config));
    }
  }

  return result;
}

/**
 * 从文件中读取指定块
 * @param file File对象
 * @param offset 偏移量
 * @param size 读取大小
 * @returns Promise<string>
 */
function readFileChunk(file: File, offset: number, size: number): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    const blob = file.slice(offset, offset + size);

    reader.onload = (e) => {
      resolve((e.target?.result as string) || "");
    };

    reader.onerror = () => {
      reject(new Error("文件读取失败"));
    };

    reader.readAsText(blob, "utf-8");
  });
}

/**
 * 创建章节对象
 * @param chapterNumber 章节号
 * @param title 章节标题
 * @param content 章节内容
 * @param config 配置
 * @returns Chapter对象
 */
function createChapterObject(
  chapterNumber: number,
  title: string,
  content: string,
  config: Required<TxtToMockOptions>,
): Chapter {
  return {
    id: `${config.novelId}-${chapterNumber}`,
    novelId: config.novelId,
    chapterNumber,
    title: `${config.novelTitle} ${title}`,
    content: content,
    wordCount: countChineseCharacters(content),
    isVip: chapterNumber > config.freeChapters,
    price: chapterNumber > config.freeChapters ? config.vipPrice : 0,
    isFree: chapterNumber <= config.freeChapters,
    createdAt: generateRandomDate(),
    updatedAt: generateRandomDate(),
  };
}

/**
 * 计算中文字符数
 * @param text 文本内容
 * @returns 中文字符数
 */
export function countChineseCharacters(text: string): number {
  return (text.match(/[\u4e00-\u9fa5]/g) || []).length;
}

/**
 * 生成随机日期
 * @param startYear 开始年份，默认2020
 * @param endDate 结束日期，默认当前时间
 * @returns ISO格式日期字符串
 */
export function generateRandomDate(startYear: number = 2020, endDate: Date = new Date()): string {
  const start = new Date(startYear, 0, 1);
  const randomTime = start.getTime() + Math.random() * (endDate.getTime() - start.getTime());
  return new Date(randomTime).toISOString();
}

/**
 * 验证章节数据
 * @param chapters 章节数组
 * @returns 验证结果
 */
export function validateChapters(chapters: Chapter[]): {
  isValid: boolean;
  errors: string[];
  statistics: {
    totalChapters: number;
    freeChapters: number;
    vipChapters: number;
    totalWords: number;
    averageWords: number;
  };
} {
  const errors: string[] = [];
  const statistics = {
    totalChapters: chapters.length,
    freeChapters: 0,
    vipChapters: 0,
    totalWords: 0,
    averageWords: 0,
  };

  chapters.forEach((chapter, index) => {
    // 检查必需字段
    if (!chapter.id) errors.push(`第${index + 1}个章节缺少ID`);
    if (!chapter.title) errors.push(`第${index + 1}个章节缺少标题`);
    if (!chapter.content) errors.push(`第${index + 1}个章节缺少内容`);
    if (chapter.chapterNumber !== index + 1) {
      errors.push(`第${index + 1}个章节编号不正确`);
    }

    // 统计信息
    if (chapter.isFree) {
      statistics.freeChapters++;
    } else {
      statistics.vipChapters++;
    }
    statistics.totalWords += chapter.wordCount;
  });

  statistics.averageWords = Math.round(statistics.totalWords / statistics.totalChapters);

  return {
    isValid: errors.length === 0,
    errors,
    statistics,
  };
}

/**
 * 导出章节数据为JSON文件
 * @param chapters 章节数组
 * @param filename 文件名
 */
export function exportChaptersToJson(
  chapters: Chapter[],
  filename: string = "chapters.json",
): void {
  const dataStr = JSON.stringify(chapters, null, 2);
  const dataBlob = new Blob([dataStr], { type: "application/json" });

  const link = document.createElement("a");
  link.href = URL.createObjectURL(dataBlob);
  link.download = filename;
  link.click();

  URL.revokeObjectURL(link.href);
}

/**
 * 预览章节数据（返回前几章用于预览）
 * @param chapters 章节数组
 * @param count 预览数量，默认5章
 * @returns 预览章节数组
 */
export function previewChapters(chapters: Chapter[], count: number = 5): Chapter[] {
  return chapters.slice(0, count);
}

// 使用示例和工具函数
export const TxtToMockUtils = {
  // 常用的章节标题正则表达式
  chapterPatterns: {
    standard: /(第[一二三四五六七八九十百千万零\d]+章[^\n]*)/g,
    withSpace: /(第\s*[一二三四五六七八九十百千万零\d]+\s*章[^\n]*)/g,
    english: /(Chapter\s*\d+[^\n]*)/gi,
    simple: /(\d+[^\n]*)/g,
  },

  // 数字转换工具
  chineseNumbers: {
    零: 0,
    一: 1,
    二: 2,
    三: 3,
    四: 4,
    五: 5,
    六: 6,
    七: 7,
    八: 8,
    九: 9,
    十: 10,
    百: 100,
    千: 1000,
    万: 10000,
  },

  // 转换中文数字为阿拉伯数字
  parseChineseNumber(chinese: string): number {
    // 简化版本，实际使用时可能需要更复杂的解析
    const num = parseInt(chinese.replace(/[^\d]/g, ""));
    return isNaN(num) ? 0 : num;
  },
};

// 导出主要函数
export default {
  convertTxtToMock,
  processLargeTxt,
  countChineseCharacters,
  generateRandomDate,
  validateChapters,
  exportChaptersToJson,
  previewChapters,
  TxtToMockUtils,
};
